import os
import sys
from loguru import logger
from dotenv import load_dotenv

load_dotenv(override=True) # 加载环境变量

# 获取当前环境
ENVIRONMENT = os.getenv("ENVIRONMENT")

if ENVIRONMENT == "dev":
    LOG_LEVEL = "DEBUG"
elif ENVIRONMENT == "test":
    LOG_LEVEL = "INFO"
elif ENVIRONMENT == "prod":
    LOG_LEVEL = "INFO"

# 项目根目录
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# 配置loguru日志记录
def configure_logging():
    logger.remove()  # 移除默认的日志记录器

    # 控制台输出配置 - 包含颜色区分和易视格式
    logger.add(
        sys.stdout,
        level=LOG_LEVEL,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | "
               "<level>{message}</level> | <yellow>{file}:{line}</yellow>",
        colorize=True,
        enqueue=True,
        backtrace=True,
        diagnose=True,
    )

    # 详细日志文件输出配置 - 只记录 DEBUG 及以上级别
    logger.add(
        os.path.join(ROOT_DIR, "output_logs", "{time:YYYY-MM-DD}.log"),
        rotation="1 day",
        retention="10 days",
        level=LOG_LEVEL,
        format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {file}:{function}:{line} - {message}",
        enqueue=True,
        backtrace=True,
        diagnose=True
    )

    # 错误日志单独保存，包含文件名、函数名、行号和完整的异常信息
    logger.add(
        os.path.join(ROOT_DIR, "output_logs", "errors.log"),
        level="ERROR",
        rotation="1 week",
        retention="1 month",
        format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {file}:{function}:{line} - {message}\n{exception}",
        enqueue=True,
        backtrace=True,
        diagnose=True
    )


configure_logging()